#include "pfo.h"

#if (GPIO_P07_PFO_MODE)
void pfo_init(void)
{
    MODIFY_REG(CLKCON1, PFOU_CE, PFOU_CE);
    MODIFY_REG(PRCCON0, PRCFC_CLR, CONFIG_PFO_CENTER_FREQ);

    #if CONFIG_DUTY_ADJ
        MODIFY_REG(PRCCON1, (PRCDIV_CLR | PRODUTY_EN), (CONFIG_PFO_CENTER_DIV | PRODUTY_EN));
    #else
        MODIFY_REG(PRCCON1, PRCDIV_CLR, CONFIG_PFO_CENTER_DIV);
    #endif

    /* large driver */
    if ((sys_get_version() & 0x08) != 0)
        MODIFY_REG(P1OM, 0x80, 0x80);

    // source 20ma
    MODIFY_REG(PDRV0, (0x3 << 1), (0x0 << 1));
    // sink 40ma
    MODIFY_REG(PDRV1, (0x3 << 6), (0x1 << 6));
    // DDL enable, source PRCCLK
    MODIFY_REG(DLLCON0, DLLCON0_CLR, DLLEN);

    MODIFY_REG(PRCCON0, PRCEN, PRCEN);

    /* Spread Spectrum enable; Hershey Kiss mode */
    MODIFY_REG(PRCCON2, PRCCON2_CLR, (SSEN | SFMODE | SSSPEED_1 | SSRANGE_16));
}

void pfo_exit(void)
{
    _P07_IO_MODE();
    CLEAR_BIT(PRCCON0, PRCEN);
    CLEAR_BIT(CLKCON1, PFOU_CE);
}

void pfo_enable(void)
{
    _P07_IO_PFO();
}

void pfo_disable(void)
{
    _P07_IO_MODE();
    /* output low to resolve the Peak current */
    _P07_IO_OUTPUT();
    _P07_EN(low);
}

/**
 * @brief 调整PRCFREQ寄存器
 * 
 * @param regval 0-2047
 */
void pfo_set_freq(uint16_t regval)
{
    regval = regval;

    MODIFY_REG(PRCCON1, PRCFREQE_8T10_CLR, ((regval >> 3) & 0xE0));
    WRITE_REG(PRCFREQL, regval & 0xFF);
}

void pfo_set_duty(enum pfo_duty_enum duty)
{
#if CONFIG_DUTY_ADJ
    MODIFY_REG(DLLCON0, DUTY0_CLR, duty);
#else
    duty = duty;
#endif
}
#endif
